/**
 * 全部课程页面组件
 * 提供课程展示功能，包括：
 * - 轮播图展示
 * - 课程分类筛选
 * - 课程列表展示
 * - 无限滚动加载
 * - 响应式布局支持
 */

<template>
  <div class="all-courses-container">
    <!-- 使用轮播图组件 -->
    <MainBanner :banners="mainBanners" />

    <!-- 课程分类标签 -->
    <div class="section all-courses">
      <div class="container">
        <div class="section-header">
          <div class="section-title">
            <span class="title-icon"></span>
            <h2>全部课程</h2>
          </div>
          <div class="section-tabs">
            <div 
              v-for="category in categories" 
              :key="category.id"
              class="tab" 
              :class="{ active: selectedCategory === category.id }"
              @click="filterByCategory(category.id)"
            >{{ category.name }}</div>
          </div>
        </div>
        
        <!-- 加载状态显示 -->
        <div v-if="initialLoading" class="loading-container">
          <div class="loading-spinner"></div>
          <p>加载中...</p>
        </div>
        
        <!-- 错误状态显示 -->
        <div v-else-if="error" class="error-container">
          <p>{{ error }}</p>
          <button @click="fetchCourses" class="retry-button">重试</button>
        </div>
        
        <!-- 课程列表展示 -->
        <div v-else class="course-list">
          <div 
            v-for="course in displayedCourses" 
            :key="course.courseId" 
            class="course-card"
            @click="goToCourseDetail(course.courseId)"
          >
            <!-- 课程封面图 -->
            <div class="course-image" :style="{ backgroundImage: `url(${getImageUrl(course)})` }">
              <div class="course-tag" v-if="course.recommendWeight >= 10">热门</div>
              <span v-if="course.price === 0" class="course-tag">免费</span>
            </div>
            <!-- 课程信息 -->
            <div class="course-info">
              <h3 class="course-title">{{ course.title }}</h3>
              <div class="course-meta">
                <span class="course-school">分类: {{ getCategoryName(course.categoryId) }}</span>
                <span class="course-teacher">教师ID: {{ course.teacherId }}</span>
              </div>
              <div class="course-stats">
                <div class="stat">
                  <i class="el-icon-user"></i>
                  <span>学习人数: {{ course.studyPeople || '暂无数据' }}</span>
                </div>
              </div>
              <div class="course-price" :class="{'free': course.price === 0}">
                {{ course.price === 0 ? '免费' : '¥' + course.price.toFixed(2) }}
              </div>
            </div>
          </div>
        </div>
        
        <!-- 空状态显示 -->
        <div v-if="!initialLoading && !error && displayedCourses.length === 0" class="empty-container">
          <p>暂无课程信息</p>
        </div>

        <!-- 分页组件 -->
        <div class="pagination-container" v-if="!initialLoading && !error && displayedCourses.length > 0">
          <el-pagination
            v-model:current-page="currentPage"
            :total="totalCourses"
            layout="total, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { getHotCourses } from '@/api/course'
import { getUserName } from '@/api/user'
import MainBanner from '@/components/common/MainBanner.vue'

export default {
  name: 'AllCoursesView',
  components: {
    MainBanner
  },
  
  setup() {
    // 状态管理
    const allCourses = ref([])                  // 所有课程数据
    const displayLimit = ref(12)                // 每页显示数量
    const initialLoading = ref(true)            // 初始加载状态
    const isLoadingMore = ref(false)            // 加载更多状态
    const error = ref('')                       // 错误信息
    const totalCourses = ref(0)                 // 课程总数
    const currentPage = ref(1)                  // 当前页码
    const pageSize = ref(16)                    // 每页显示数量固定为20
    const selectedCategory = ref(0)             // 选中的分类
    const userName = ref('')                    // 用户名
    const avatarUrl = ref('')                   // 头像URL
    const router = useRouter()                  // 路由实例
    const hasMoreCourses = ref(true)            // 是否还有更多课程
    const loadMoreTrigger = ref(null)           // 滚动加载触发器
    const intersectionObserver = ref(null)      // 交叉观察器
    
    // 课程分类定义
    const categories = [
      { id: 0, name: '全部' },
      { id: 1, name: '学术' },
      { id: 2, name: '技术与工程' },
      { id: 3, name: '商业与管理' },
      { id: 4, name: '艺术与设计' },
      { id: 5, name: '职业技能' },
      { id: 6, name: '健康与医学' },
      { id: 7, name: '语言与文化' },
      { id: 8, name: '科技与未来趋势' },
      { id: 9, name: '体育与健身' }
    ]
    
    // 防抖定时器
    let scrollDebounceTimer = null
    
    // 计算当前显示的课程列表
    const displayedCourses = computed(() => {
      // 先根据分类筛选
      const filteredCourses = selectedCategory.value === 0 
        ? allCourses.value 
        : allCourses.value.filter(course => course.categoryId === selectedCategory.value)
      
      // 返回筛选后的数据
      return filteredCourses
    })
    
    /**
     * 获取分类名称
     * @param {number} categoryId - 分类ID
     * @returns {string} 分类名称
     */
    const getCategoryName = (categoryId) => {
      const category = categories.find(c => c.id === categoryId)
      return category ? category.name : `分类${categoryId}`
    }
    
    /**
     * 获取课程图片URL
     * @param {Object} course - 课程对象
     * @returns {string} 图片URL
     */
    const getImageUrl = (course) => {
      return course.titleImg || course.ossImages || 
        (course.details?.startsWith('http') ? course.details : '')
    }
    
    /**
     * 切换课程分类
     * @param {number} categoryId - 分类ID
     */
    const filterByCategory = (categoryId) => {
      selectedCategory.value = categoryId
    }
    
    /**
     * 处理每页显示数量变化
     * @param {number} size - 新的每页显示数量
     */
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1 // 切换每页显示数量时重置页码
      fetchCourses()
    }
    
    /**
     * 处理页码变化
     * @param {number} page - 新的页码
     */
    const handleCurrentChange = (page) => {
      currentPage.value = page
      fetchCourses()
    }
    
    /**
     * 获取课程数据
     * 从服务器获取课程列表，支持分页加载
     */
    const fetchCourses = async () => {
      initialLoading.value = true
      error.value = ''
      
      try {
        // 确保传递正确的分页参数
        const response = await getHotCourses(currentPage.value, pageSize.value)
        
        if (response?.code === 200 && response.data?.records) {
          // 直接使用返回的数据
          allCourses.value = response.data.records
          totalCourses.value = response.data.total
          
          // 更新分页信息
          currentPage.value = response.data.current
          pageSize.value = response.data.size
        } else {
          error.value = response?.message || '获取课程数据失败'
        }
      } catch (err) {
        error.value = '获取课程数据失败，请稍后重试'
      } finally {
        initialLoading.value = false
      }
    }
    
    /**
     * 加载更多课程
     * 根据当前分类和显示限制加载更多课程
     */
    const loadMoreCourses = () => {
      if (isLoadingMore.value || !hasMoreCourses.value) return
      
      const filteredCourses = selectedCategory.value === 0 
        ? allCourses.value 
        : allCourses.value.filter(course => course.categoryId === selectedCategory.value)
      
      if (filteredCourses.length > displayLimit.value) {
        const remainingCourses = filteredCourses.length - displayLimit.value
        displayLimit.value += Math.min(remainingCourses, 20)
      } else if (hasMoreCourses.value) {
        fetchCourses()
      }
    }
    
    /**
     * 检查是否需要加载更多
     * 根据当前显示状态和分类决定是否加载更多课程
     */
    const checkLoadMore = () => {
      if (scrollDebounceTimer) {
        clearTimeout(scrollDebounceTimer)
      }
      
      scrollDebounceTimer = setTimeout(() => {
        if (loadMoreTrigger.value) {
          const rect = loadMoreTrigger.value.getBoundingClientRect()
          if (rect.top < window.innerHeight + 100) {
            loadMoreCourses()
          }
        }
      }, 100)
    }
    
    /**
     * 设置交叉观察器
     * 用于监听滚动加载触发器的可见性
     */
    const setupIntersectionObserver = () => {
      if (intersectionObserver.value) {
        intersectionObserver.value.disconnect()
      }
      
      intersectionObserver.value = new IntersectionObserver((entries) => {
        if (entries[0].isIntersecting) {
          loadMoreCourses()
        }
      }, {
        root: null,
        rootMargin: '100px',
        threshold: 0.1
      })
      
      if (loadMoreTrigger.value) {
        intersectionObserver.value.observe(loadMoreTrigger.value)
      }
    }
    
    // 轮播图数据
    const mainBanners = ref([
      {
        title: '探索知识的海洋',
        desc: '来自全国顶尖高校的优质课程',
        buttonText: '立即体验',
        bgImage: 'https://edu-image.nosdn.127.net/C7F81100F90F8DB85704C901C4CFFC9D.jpg'
      },
      {
        title: '突破自我，提升实力',
        desc: '专业认证课程，提升就业竞争力',
        buttonText: '了解更多',
        bgImage: 'https://edu-image.nosdn.127.net/249dc9d7-fbd5-41fb-8e1d-a92c79be05c8.jpg'
      },
      {
        title: '名师指导，助力成长',
        desc: '知名教授在线授课，答疑解惑',
        buttonText: '现在开始',
        bgImage: 'https://edu-image.nosdn.127.net/30F964990D6937557C05DD9EDD6C5BA3.jpg'
      }
    ])
    
    /**
     * 获取用户信息
     * 从服务器获取当前用户的基本信息
     */
    const fetchUserInfo = async () => {
      try {
        const response = await getUserName()
        if (response && response.code === 200 && response.data) {
          userName.value = response.data.userName || '用户'
          
          // 处理头像URL
          if (response.data.avatarUrl) {
            avatarUrl.value = response.data.avatarUrl.startsWith('http') 
              ? response.data.avatarUrl 
              : `${response.data.avatarUrl}`
          } else {
            avatarUrl.value = ''
          }
        }
      } catch (error) {
        userName.value = '用户'
        avatarUrl.value = ''
      }
    }
    
    /**
     * 跳转到课程详情页面
     * @param {string|number} courseId - 课程ID
     */
    const goToCourseDetail = (courseId) => {
      const courseIdStr = String(courseId)
      try {
        router.push({
          name: 'CourseDetail',
          params: { id: courseIdStr }
        }).then(() => {
          // 导航完成后延迟100ms刷新页面
          setTimeout(() => {
            window.location.reload()
          }, 1)
        })
      } catch (err) {
        error.value = '跳转失败，请重试'
      }
    }
    
    // 监听分类变化
    watch(selectedCategory, () => {
      nextTick(() => {
        setupIntersectionObserver()
        checkLoadMore()
      })
    })
    
    // 组件挂载
    onMounted(() => {
      displayLimit.value = 20
      selectedCategory.value = 0
      fetchCourses()
      fetchUserInfo()
      nextTick(() => {
        setupIntersectionObserver()
      })
    })
    
    // 组件卸载清理
    onUnmounted(() => {
      if (intersectionObserver.value) {
        intersectionObserver.value.disconnect()
      }
      if (scrollDebounceTimer) {
        clearTimeout(scrollDebounceTimer)
      }
    })
    
    return {
      // 状态
      allCourses,
      displayedCourses,
      initialLoading,
      isLoadingMore,
      error,
      totalCourses,
      currentPage,
      pageSize,
      selectedCategory,
      userName,
      avatarUrl,
      mainBanners,
      hasMoreCourses,
      loadMoreTrigger,
      categories,
      
      // 方法
      fetchCourses,
      filterByCategory,
      getImageUrl,
      getCategoryName,
      goToCourseDetail,
      fetchUserInfo,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.all-courses-container {
  min-height: 100vh;
  background-color: #f5f5f7;
}

/* 轮播图区域样式 */
.main-banner {
  width: 100%;
  margin-bottom: 40px;
}

.custom-carousel {
  width: 100%;
}

.section {
  padding: 30px 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.section-header {
  margin-bottom: 20px;
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.title-icon {
  width: 4px;
  height: 24px;
  background-color: #1890ff;
  margin-right: 12px;
  border-radius: 2px;
}

.section-title h2 {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
  letter-spacing: 1px;
}

.section-tabs {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.tab {
  cursor: pointer;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
  color: #666;
  transition: all 0.3s;
}

.tab:hover {
  background-color: #f5f7fa;
}

.tab.active {
  color: #1890ff;
  background-color: #e6f7ff;
  font-weight: 500;
}

/* 加载中、错误和空状态样式 */
.loading-container, .error-container, .empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 3rem;
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 1rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.retry-button {
  margin-top: 1rem;
  background: #1890ff;
  color: white;
  border: none;
  padding: 0.5rem 1.5rem;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
}

.retry-button:hover {
  background: #096dd9;
}

/* 课程卡片和列表样式 */
.course-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.course-card {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
}

.course-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.08);
}

.course-image {
  height: 160px;
  background-size: cover;
  background-position: center;
  position: relative;
}

.course-tag {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 4px 8px;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.course-info {
  padding: 15px;
}

.course-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 10px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.course-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
  margin-bottom: 10px;
}

.course-stats {
  display: flex;
  gap: 15px;
  margin-bottom: 10px;
}

.stat {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
  color: #666;
}

.course-price {
  font-size: 16px;
  font-weight: 600;
  color: #f56c6c;
}

.course-price.free {
  color: #67c23a;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding: 20px 0;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .course-list {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 992px) {
  .course-list {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .course-list {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .pagination-container {
    padding: 10px 0;
  }
}

@media (max-width: 480px) {
  .course-list {
    grid-template-columns: 1fr;
  }
}
</style> 